package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func ParseForm(c *gin.Context) {
	c.Request.ParseForm()
	form := c.Request.Form
	fmt.Println("-----------------------------")
	fmt.Printf("%s %s %s %s\n", "[gamebox]", c.Request.URL, ":", c.Request.Method)
	fmt.Printf("%s %s %+v\n", "[gamenox]", "request:", form)
	c.Next()
}

func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.Request.Header.Get("origin")
		c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, XMLHttpRequest, "+
			"Accept-Encoding, X-CSRF-Token, Authorization")
		if c.Request.Method == "OPTIONS" {
			c.String(200, "ok")
			return
		}
		c.Next()
	}
}

func respondWithError(code int, message string, c *gin.Context) {
	resp := map[string]string{"error": message}
	c.JSON(code, resp)
	c.Abort()
}
